import {
  batchDeleteUser,
  createUser,
  queryUserList,
  resetPassword,
  updateUser,
  userSearchExport,
  userSelectExport,
} from '@/service/user';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { App, Button, message, Space } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { defaultColumns } from './components/columns';
import RestPasswordModal from './components/RestPasswordModal';
import UserModal from './components/UserModal';

const AccountList: React.FC = () => {
  const { modal } = App.useApp();
  const actionRef = useRef<ActionType>();
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser || {};

  const [selectedKeys, setSelectedKeys] = useState<API.RuleListItem[]>([]);
  const [columns, setColumns] = useState<ProColumns<API.RuleListItem>[]>([]);

  const [totalCount, setTotalCount] = useState<number>(0);
  const [queryParams, setQueryParams] = useState<object>(null);

  // 操作标识
  const [operateType, setOperateType] = useState('');
  const [userOpen, setUserOpen] = useState(false);
  const [userModalInfo, setUserModalInfo] = useState({});
  // 重置密码-操作标识
  const [restPasswordOpen, setRestPasswordOpen] = useState(false);
  const [restPasswordModalInfo, setRestPasswordModalInfo] = useState({});

  // 添加账号 - 弹窗
  const prevAddUser = () => {
    setOperateType('add');
    setUserModalInfo({});
    setUserOpen(true);
  };
  // 删除账号
  const deleteUser = (ids) => {
    modal.confirm({
      title: '删除提示',
      content: `确定删除id为${ids.join('、')}的账号吗`,
      onOk: async () => {
        const res = await batchDeleteUser({ ids });
        if (res) {
          message.success('删除成功');
          actionRef.current?.reloadAndRest();
          return;
        }
      },
    });
  };

  // 修改账号-弹窗
  const prevUpdateUser = (item) => {
    setOperateType('edit');
    setUserModalInfo(item);
    setUserOpen(true);
  };

  // 用户新建/修改
  const userOperateFinish = async (values) => {
    const { username, roleId } = values;

    let res = null;
    if (operateType === 'add') {
      res = await createUser(values);
    } else if (operateType === 'edit') {
      res = await updateUser(userModalInfo.id, { username, roleId });
    }

    if (res) {
      message.success('操作成功');
      setUserOpen(false);
      setUserModalInfo({});
      actionRef?.current?.reloadAndRest();
    }
  };

  // 重置密码-弹窗
  const prevRestPassword = (item) => {
    console.log(item);
    setRestPasswordModalInfo(item);
    setRestPasswordOpen(true);
  };

  // 重置密码-提交
  const restPasswordFinish = async (values) => {
    const { newPassword, confirmPassword } = values;

    if (newPassword !== confirmPassword) {
      message.error('确认密码与新密码必须一致，请修改');
      return;
    }

    const res = await resetPassword({ id: restPasswordModalInfo.id, newPassword, confirmPassword });
    if (res) {
      message.success('操作成功');
      setRestPasswordOpen(false);
      setRestPasswordModalInfo({});
    }
  };

  // 查询导出
  const searchExport = () => {
    if (!totalCount) {
      message.error('列表数据为空，无法查询导出');
      return;
    }

    userSearchExport(queryParams);
  };

  // 批量导出
  const selectExport = (selectedKeys) => {
    console.log('@@@ selectedKeys', selectedKeys);
    if (!selectedKeys?.length) {
      message.error('请勾选数据');
      return;
    }

    userSelectExport({ ids: selectedKeys });
  };

  useEffect(() => {
    // 访客不展示操作按钮
    if (currentUser.roleWeight === 3) {
      defaultColumns.pop();
    } else {
      defaultColumns[defaultColumns.length - 1].render = (text, item) => {
        // 当前权限权重要小于 该条权重才能就行操作 权重越小 权限越大
        return currentUser.roleWeight < item.roleWeight || currentUser.roleWeight === 0 ? (
          <>
            <Button type="link" onClick={() => prevUpdateUser(item)}>
              修改
            </Button>
            <Button type="link" onClick={() => deleteUser([item.id])}>
              删除
            </Button>
            <Button type="link" onClick={() => prevRestPassword(item)}>
              重置密码
            </Button>
          </>
        ) : null;
      };
    }

    setColumns(defaultColumns);
  }, []);

  // 表格查询
  const tableSearch = async (params) => {
    let values = {
      ...params,
      pageNum: params.current,
      pageSize: params.pageSize,
    };
    delete values.current;

    const res = await queryUserList(values);

    setQueryParams(values);
    setTotalCount(res?.total || 0);

    return { success: true, data: res?.list || [], total: res?.total || 0 };
  };

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey={(item) => item.id}
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        request={tableSearch}
        columns={columns}
        toolBarRender={() =>
          currentUser.roleWeight === 3
            ? []
            : [
                <Button key="add" type="primary" onClick={prevAddUser}>
                  添加账号
                </Button>,
                <Button key="searchExport" type="primary" onClick={searchExport}>
                  查询导出
                </Button>,
              ]
        }
        tableAlertOptionRender={() =>
          currentUser.roleWeight === 3 ? null : (
            <Space>
              <Button key="delete" type="link" danger onClick={() => deleteUser(selectedKeys)}>
                批量删除
              </Button>
              <Button key="selectExport" type="link" onClick={() => selectExport(selectedKeys)}>
                批量导出
              </Button>
            </Space>
          )
        }
        scroll={{ x: 'max-content' }}
        rowSelection={
          currentUser.roleWeight === 3
            ? false
            : {
                onChange: (_) => {
                  setSelectedKeys(_);
                },
              }
        }
      />
      <UserModal
        modalInfo={userModalInfo}
        operateType={operateType}
        open={userOpen}
        onOpenChange={setUserOpen}
        onFinish={userOperateFinish}
      />
      <RestPasswordModal
        modalInfo={restPasswordModalInfo}
        open={restPasswordOpen}
        onOpenChange={setRestPasswordOpen}
        onFinish={restPasswordFinish}
      />
    </PageContainer>
  );
};

export default AccountList;
